package com.iflytek.aidemo.api;


import android.util.Log;

import com.iflytek.aidemo.model.ApiResponse;
import com.iflytek.aidemo.model.ImageRecord;
import com.iflytek.aidemo.model.Student;
import com.iflytek.aidemo.model.Teacher;
import com.iflytek.aidemo.model.User;
import com.iflytek.aidemo.model.WrongQuestionRecord;
import com.iflytek.aidemo.model.ClassInfo;
import com.iflytek.aidemo.util.HttpUtil;
import com.iflytek.aidemo.util.NetworkConfig;

import org.json.JSONException;
import org.json.JSONArray;
import org.json.JSONObject;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

/**
 * API服务实现类
 */
public class ApiServiceImpl implements ApiService {
    @Override
    public ApiResponse<User> login(String username, String password) {
        try {
            // 构建请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");

            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("username", username);
            requestBody.put("password", password);

            // 发送请求
            String response = HttpUtil.doPost1(NetworkConfig.getLoginUrl(), headers, requestBody.toString());

            System.out.println(response);
            if (response != null) {
                return parseLoginResponse(response);
            } else {
                return new ApiResponse<>(500, "网络请求失败", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "请求异常: " + e.getMessage(), null);
        }
    }

    // ================= 教师端 成绩相关 =================


    @Override
    public ApiResponse<Teacher> gerTeacherIdByUserId(String userId) {
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Accept", "application/json");
            String url = NetworkConfig.getTeacherIdByUserIdUrl(userId);
            System.out.println("url:"+url);
            String response = HttpUtil.doGet(url, headers);
            if (response != null) {
                return parseTeacherUserResponse(response);
            } else {
                return new ApiResponse<>(500, "网络请求失败", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "请求异常: " + e.getMessage(), null);
        }
    }

    @Override
    public ApiResponse<List<ClassInfo>> getClassesByTeacher(String teacherId) {
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Accept", "application/json");
            String url = NetworkConfig.getTeacherClassesUrl(teacherId);
            System.out.println("url"+url);
            String response = HttpUtil.doGet(url, headers);
            if (response != null) {
                return parseTeacherClassesResponse(response);
            } else {
                return new ApiResponse<>(500, "网络请求失败", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "请求异常: " + e.getMessage(), null);
        }
    }

    @Override
    public ApiResponse<org.json.JSONObject> getClassOverviewWithStudents(int classId, String date) {
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Accept", "application/json");
            String url = NetworkConfig.getClassOverviewUrl(classId, date);
            System.out.println(url);
            String response = HttpUtil.doGet(url, headers);
            if (response != null) {
                return parseClassOverviewResponse(response);
            } else {
                return new ApiResponse<>(500, "网络请求失败", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "请求异常: " + e.getMessage(), null);
        }
    }

    @Override
    public ApiResponse<java.util.List<ImageRecord>> getStudentScoreDetail(int studentId, String date) {
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Accept", "application/json");
            String url = NetworkConfig.getStudentScoreDetailUrl(studentId, date);
            String response = HttpUtil.doGet(url, headers);
            if (response != null) {
                return parseStudentScoreDetailResponse(response);
            } else {
                return new ApiResponse<>(500, "网络请求失败", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "请求异常: " + e.getMessage(), null);
        }
    }

    @Override
    public ApiResponse<User> register(String username, String password, int userType) {
        try {
            // 构建请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");

            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("username", username);
            requestBody.put("password", password);
            requestBody.put("userType", userType);

            // 发送请求
            String response = HttpUtil.doPost1(NetworkConfig.getRegisterUrl(), headers, requestBody.toString());

            if (response != null) {
                return parseRegisterResponse(response);
            } else {
                return new ApiResponse<>(500, "网络请求失败", null);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "请求异常: " + e.getMessage(), null);
        }
    }


    //上传答题情况
    @Override
    public ApiResponse<ImageRecord> uploadImageRecord(int studentId, String recordImagePath, int count, int countCorrect, String submitTime) {
        try {
            // 构建请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");

            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("studentId", studentId);
            requestBody.put("recordImagePath", recordImagePath);
            requestBody.put("count", count);
            requestBody.put("countCorrect", countCorrect);
            requestBody.put("submitTime", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

            // 发送请求
            String response = HttpUtil.doPost1(NetworkConfig.getRecordsUrl(), headers, requestBody.toString());

            System.out.println(response);
            if (response != null) {
                return parseImageRecordResponse(response);
            } else {
                return new ApiResponse<>(500, "网络请求失败", null);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "请求异常: " + e.getMessage(), null);
        }
    }

    @Override
    public ApiResponse<WrongQuestionRecord> uploadWrongQuestion(int studentId, int recordId, String wrongImagePath, String answer, String question, LocalDate date) {
        try {
            // 构建请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");

            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("studentId", studentId);
            requestBody.put("recordId", recordId);
            requestBody.put("wrongImagePath", wrongImagePath);
            requestBody.put("answer", answer);
            requestBody.put("question", question);
            requestBody.put("date",date);

            // 发送请求
            String response = HttpUtil.doPost1(NetworkConfig.uploadWrongUrl(), headers, requestBody.toString());

            System.out.println(response);
            if (response != null) {
                return parseWrongQuestionResponse(response);
            } else {
                return new ApiResponse<>(500, "网络请求失败", null);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "请求异常: " + e.getMessage(), null);
        }
    }

    /**
     * 根据学生id获取错题
     * @param studentId 学生ID
     * @return
     */

    @Override
    public ApiResponse<java.util.List<WrongQuestionRecord>> getWrongQuestionsByStudentId(String studentId) {
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");
            String url = NetworkConfig.getWrongListUrl() + "/" + studentId;
            String response = HttpUtil.doGet(url, headers);
            if (response != null) {
                return parseWrongQuestionListResponse(response);
            } else {
                return new ApiResponse<>(500, "网络请求失败", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "请求异常: " + e.getMessage(), null);
        }
    }

    @Override
    public ApiResponse<Boolean> completeWrongQuestions(int studentId) {
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");

            String url = NetworkConfig.getCompleteWrongUrl() + "/" + studentId;

            // 构建请求体 JSON
//            org.json.JSONObject body = new org.json.JSONObject();
//            body.put("studentId", studentId);
//            org.json.JSONArray idArray = new org.json.JSONArray();
//            if (wrongQuestionIds != null) {
//                for (Integer id : wrongQuestionIds) {
//                    if (id != null) idArray.put(id.intValue());
//                }
//            }
//            body.put("wrongQuestionIds", idArray);


            String response = HttpUtil.doGet(url, headers);
            if (response != null) {
                return parseCompleteWrongResponse(response);
            } else {
                return new ApiResponse<>(500, "网络请求失败", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "请求异常: " + e.getMessage(), false);
        }
    }

    /**
     * 解析登录响应
     */
    private ApiResponse<User> parseLoginResponse(String response) {
        try {
            JSONObject jsonResponse = new JSONObject(response);
            int code = jsonResponse.optInt("code", 500);
            String message = jsonResponse.optString("message", "未知错误");

            if (code == 200) {
                JSONObject data = jsonResponse.optJSONObject("data");
                if (data != null) {
                    User user = new User();
                    user.setId(data.optString("userId"));
                    user.setUserName(data.optString("username"));
                    user.setUserType(data.optString("userType"));

                    return new ApiResponse<>(code, message, user);
                }
            }

            return new ApiResponse<>(code, message, null);

        } catch (JSONException e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "响应解析失败", null);
        }
    }

    /**
     * 解析注册响应
     */
    private ApiResponse<User> parseRegisterResponse(String response) {
        try {
            JSONObject jsonResponse = new JSONObject(response);
            int code = jsonResponse.optInt("code", 500);
            String message = jsonResponse.optString("message", "未知错误");

            if (code == 200) {
                JSONObject data = jsonResponse.optJSONObject("data");
                if (data != null) {
                    User user = new User();
                    user.setId(data.optString("userId"));
                    user.setUserName(data.optString("username"));
                    user.setUserType(data.optString("userType"));

                    return new ApiResponse<>(code, message, user);
                }
            }

            return new ApiResponse<>(code, message, null);

        } catch (JSONException e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "响应解析失败", null);
        }
    }

    /**
     * 解析检查响应
     */
    private ApiResponse<Boolean> parseCheckResponse(String response) {
        try {
            JSONObject jsonResponse = new JSONObject(response);
            int code = jsonResponse.optInt("code", 500);
            String message = jsonResponse.optString("message", "未知错误");

            if (code == 200) {
                boolean available = jsonResponse.optJSONObject("data").optBoolean("available", false);
                return new ApiResponse<>(code, message, available);
            }

            return new ApiResponse<>(code, message, false);

        } catch (JSONException e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "响应解析失败", false);
        }
    }

    /**
     * 解析图片记录上传响应
     *
     * @param response 响应字符串
     * @return ApiResponse对象，包含解析后的ImageRecord数据
     */
    private ApiResponse<ImageRecord> parseImageRecordResponse(String response) {
        try {
            JSONObject jsonResponse = new JSONObject(response);
            int code = jsonResponse.optInt("code", 500); // 默认值500
            String message = jsonResponse.optString("message", "未知错误"); // 默认值"未知错误"

            if (code == 200) {
                JSONObject dataObj = jsonResponse.optJSONObject("data");
                if (dataObj != null) {
                    ImageRecord imageRecord = new ImageRecord();
                    imageRecord.setId(dataObj.optInt("recordId", 0)); // 默认值0
                    imageRecord.setStudentId(dataObj.optInt("studentId", 0)); // 默认值0
                    imageRecord.setRecordImagePath(dataObj.optString("recordImagePath", "")); // 默认值空字符串
                    imageRecord.setCount(dataObj.optInt("count", 0)); // 默认值0
                    imageRecord.setCountCorrect(dataObj.optInt("countCorrect", 0)); // 默认值0
                    imageRecord.setSubmitTime(dataObj.optString("submitTime", "")); // 默认值空字符串

                    return new ApiResponse<>(code, message, imageRecord);
                }
            }

            return new ApiResponse<>(code, message, null);

        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "解析响应失败: " + e.getMessage(), null);
        }
    }

    /**
     * 解析错题上传响应
     */
    private ApiResponse<WrongQuestionRecord> parseWrongQuestionResponse(String response) {
        try {
            JSONObject jsonResponse = new JSONObject(response);
            int code = jsonResponse.optInt("code", 500);
            String message = jsonResponse.optString("message", "未知错误");

            // 处理非200状态码
            if (code != 200) {
                Log.e("ResponseParser", "服务器返回错误码: " + code + ", 信息: " + message);
                return new ApiResponse<>(code, message, null);
            }
            if (code == 200) {
                Log.e("ResponseParser", "服务器返回: " + code + ", 信息: " + message);
                JSONObject data = jsonResponse.optJSONObject("data");
                if (data != null) {
                    WrongQuestionRecord wrongQuestion = new WrongQuestionRecord();
                    wrongQuestion.setWrongId(data.optInt("wrongId"));
                    wrongQuestion.setStudentId(data.optInt("studentId"));
                    wrongQuestion.setRecordId(data.optInt("recordId"));
                    wrongQuestion.setWrongImagePath(data.optString("wrongImagePath"));
                    wrongQuestion.setAnswer(data.optString("answer"));
                    wrongQuestion.setQuestion(data.optString("question"));
                    wrongQuestion.setDate(data.optString("date"));

                    return new ApiResponse<>(code, message, wrongQuestion);
                }
            }

            return new ApiResponse<>(code, message, null);

        } catch (JSONException e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "响应解析失败", null);
        }
    }

    /**
     * 解析错题集响应
     * @param response
     * @return
     */
    private ApiResponse<java.util.List<WrongQuestionRecord>> parseWrongQuestionListResponse(String response) {
        try {
            org.json.JSONObject jsonResponse = new org.json.JSONObject(response);
            int code = jsonResponse.optInt("code", 500);
            String message = jsonResponse.optString("message", "未知错误");
            java.util.List<WrongQuestionRecord> list = new java.util.ArrayList<>();
            org.json.JSONArray dataArr = jsonResponse.optJSONArray("data");
            if (dataArr != null) {
                for (int i = 0; i < dataArr.length(); i++) {
                    org.json.JSONObject data = dataArr.getJSONObject(i);
                    WrongQuestionRecord wrongQuestion = new WrongQuestionRecord();
                    wrongQuestion.setWrongId(data.optInt("wrongId"));
                    wrongQuestion.setStudentId(data.optInt("studentId"));
                    wrongQuestion.setRecordId(data.optInt("recordId"));
                    wrongQuestion.setWrongImagePath(data.optString("wrongImagePath"));
                    wrongQuestion.setAnswer(data.optString("answer"));
                    wrongQuestion.setQuestion(data.optString("question"));
                    wrongQuestion.setDate(data.optString("date"));
                    list.add(wrongQuestion);
                }
            }
            return new ApiResponse<>(code, message, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "响应解析失败", null);
        }
    }

    /**
     * 解析提交完成错题响应
     * 与其他解析方法保持一致风格
     */
    private ApiResponse<Boolean> parseCompleteWrongResponse(String response) {
        try {
            JSONObject jsonResponse = new JSONObject(response);
            int code = jsonResponse.optInt("code", 500);
            String message = jsonResponse.optString("message", "未知错误");

            boolean success = false;
            if (code == 200) {
                Object data = jsonResponse.opt("data");
                if (data instanceof Boolean) {
                    success = (Boolean) data;
                } else if (data instanceof JSONObject) {
                    success = ((JSONObject) data).optBoolean("success", true);
                } else {
                    success = true; // 仅凭code判断成功
                }
            }
            return new ApiResponse<>(code, message, success);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "响应解析失败", false);
        }
    }

    // ================= 解析：教师端 成绩相关 =================

    private ApiResponse<Teacher> parseTeacherUserResponse(String response){
        try {
            JSONObject jsonResponse = new JSONObject(response);
            int code = jsonResponse.optInt("code", 500); // 默认值500
            String message = jsonResponse.optString("message", "未知错误"); // 默认值"未知错误"
            if (code == 200) {
                JSONObject dataObj = jsonResponse.optJSONObject("data");
                if (dataObj != null) {
                    Teacher teacher = new Teacher();
                    teacher.setTeacherId(dataObj.optString("teacherId", "0")); // 默认值0
                    return new ApiResponse<>(code, message, teacher);
                }
            }
            return new ApiResponse<>(code, message, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "响应解析失败", null);
        }
    }

    private ApiResponse<java.util.List<com.iflytek.aidemo.model.ClassInfo>> parseTeacherClassesResponse(String response) {
        try {
            JSONObject json = new JSONObject(response);
            int code = json.optInt("code", 500);
            String message = json.optString("message", "未知错误");
            java.util.List<com.iflytek.aidemo.model.ClassInfo> list = new java.util.ArrayList<>();
            JSONArray dataArr = json.optJSONArray("data");
            if (dataArr != null) {
                for (int i = 0; i < dataArr.length(); i++) {
                    JSONObject obj = dataArr.optJSONObject(i);
                    if (obj != null) {
                        com.iflytek.aidemo.model.ClassInfo ci = new com.iflytek.aidemo.model.ClassInfo();
                        ci.setClassId(obj.optInt("classId"));
                        ci.setClassName(obj.optString("className"));
                        list.add(ci);
                    }
                }
            }
            return new ApiResponse<>(code, message, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "响应解析失败", null);
        }
    }

    private ApiResponse<org.json.JSONObject> parseClassOverviewResponse(String response) {
        try {
            JSONObject json = new JSONObject(response);
            int code = json.optInt("code", 500);
            String message = json.optString("message", "未知错误");
            JSONObject data = json.optJSONObject("data");
            return new ApiResponse<>(code, message, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "响应解析失败", null);
        }
    }

    private ApiResponse<java.util.List<ImageRecord>> parseStudentScoreDetailResponse(String response) {
        try {
            JSONObject json = new JSONObject(response);
            int code = json.has("code") ? json.optInt("code", 500) : (json.optBoolean("success", false) ? 200 : 500);
            String message = json.has("message") ? json.optString("message", "未知错误") : (code == 200 ? "success" : "error");

            java.util.List<ImageRecord> list = new java.util.ArrayList<>();
            JSONArray dataArr = json.optJSONArray("data");
            if (dataArr != null) {
                for (int i = 0; i < dataArr.length(); i++) {
                    JSONObject obj = dataArr.optJSONObject(i);
                    if (obj == null) continue;
                    ImageRecord ir = new ImageRecord();
                    ir.setId(obj.optInt("recordId", 0));
                    ir.setStudentId(obj.optInt("studentId", 0));
                    ir.setRecordImagePath(obj.optString("recordImagePath", ""));
                    ir.setCount(obj.optInt("count", 0));
                    ir.setCountCorrect(obj.optInt("countCorrect", 0));
                    ir.setSubmitTime(obj.optString("submitTime", ""));
                    list.add(ir);
                }
            }
            return new ApiResponse<>(code, message, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "响应解析失败", null);
        }
    }

    // ================= 教师端 班级管理 =================
// 在 ApiServiceImpl.java 中添加实现
    @Override
    public ApiResponse<org.json.JSONObject> getStudentsByClass(Long classId) {
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Accept", "application/json");

            // 构建请求URL（与后端接口路径 /class/{classId} 匹配）
            String url = NetworkConfig.getStudentsByClassUrl(classId);
            Log.d("ApiService", "查询班级学生列表URL: " + url);

            // 发送GET请求
            String response = HttpUtil.doGet(url, headers);

            if (response != null) {
                return parseStudentsByClassResponse(response);
            } else {
                return new ApiResponse<>(500, "网络请求失败", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "请求异常: " + e.getMessage(), null);
        }
    }

    // 添加响应解析方法
    private ApiResponse<org.json.JSONObject> parseStudentsByClassResponse(String response) {
        try {
            JSONObject jsonResponse = new JSONObject(response);
            // 解析后端返回的code（注意后端可能返回字符串类型的code，需转换为int）
            int code;
            try {
                code = Integer.parseInt(jsonResponse.optString("code", "500"));
            } catch (NumberFormatException e) {
                code = 500; // 解析失败时默认服务器错误
            }
            String message = jsonResponse.optString("message", "未知错误");

            // 提取数据部分（学生列表在data字段中）
            JSONObject data = jsonResponse.optJSONObject("data");
            // 兼容后端可能直接返回数组的情况（如果data是数组则包装为JSONObject）
            if (data == null) {
                JSONArray studentsArray = jsonResponse.optJSONArray("data");
                if (studentsArray != null) {
                    data = new JSONObject();
                    data.put("students", studentsArray);
                }
            }

            return new ApiResponse<>(code, message, data);
        } catch (JSONException e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "响应解析失败: " + e.getMessage(), null);
        }
    }

    @Override
    public ApiResponse<User> createStudent(String username, String password) {
        try {
            // 构建请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");

            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("username", username);
            requestBody.put("password", password);

            // 发送请求
            String response = HttpUtil.doPost1(NetworkConfig.getCreateStudentUrl(), headers, requestBody.toString());

            System.out.println(response);
            if (response != null) {
                return parseLoginResponse(response);
            } else {
                return new ApiResponse<>(500, "网络请求失败", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "请求异常: " + e.getMessage(), null);
        }
    }

    @Override
    public ApiResponse<Boolean> addStudentToClass(long classId, long studentId) {
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            headers.put("Accept", "application/json");

            // 构建请求参数（表单形式）
            String params = "studentId=" + studentId;

            // 构建URL：BASE_URL + "/{classId}/add-student"
            String url = NetworkConfig.getAddStudentToClassUrl(classId);

            String response = HttpUtil.doPost1(url, headers, params);
            return parseCommonResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "添加到班级异常: " + e.getMessage(), false);
        }
    }

    // 通用响应解析方法
    private ApiResponse<Boolean> parseCommonResponse(String response) {
        try {
            JSONObject json = new JSONObject(response);
            int code = Integer.parseInt(json.optString("code", "500"));
            String message = json.optString("message", "操作失败");
            boolean success = json.optBoolean("data", false);

            return new ApiResponse<>(code, message, success);
        } catch (JSONException e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "解析响应失败", false);
        }
    }

    /**
     * 解析添加学生到班级响应
     */
    private ApiResponse<Boolean> parseAddStudentToClassResponse(String response) {
        try {
            JSONObject jsonResponse = new JSONObject(response);
            int code = jsonResponse.optInt("code", 500);
            String message = jsonResponse.optString("message", "添加失败");

            boolean success = code == 200 && jsonResponse.optBoolean("success", false);
            return new ApiResponse<>(code, message, success);
        } catch (JSONException e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "解析添加班级响应失败", false);
        }
    }

    @Override
    public ApiResponse<Boolean> removeStudentFromClass(Long classId, Long studentId) {
        try {
            // 构建请求头（与现有接口风格一致）
            Map<String, String> headers = new HashMap<>();
            headers.put("Accept", "application/json");

            // 构建请求URL（匹配后端 /{id} 路径）
            String url = NetworkConfig.getDeleteStudentUrl(studentId);
            Log.d("ApiService", "删除学生URL: " + url);

            // 发送DELETE请求
            String response = HttpUtil.doDelete(url, headers);
            Log.d("ApiService", "删除学生URL2: " + url + response);

            if (response != null) {
                return parseDeleteStudentResponse(response);
            } else {
                return new ApiResponse<>(500, "删除失败：网络请求为空", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "删除异常：" + e.getMessage(), false);
        }
    }

    /**
     * 解析删除学生的响应
     */
    private ApiResponse<Boolean> parseDeleteStudentResponse(String response) {
        try {
            JSONObject jsonResponse = new JSONObject(response);
            // 解析后端返回的字符串类型code
            int code;
            try {
                code = Integer.parseInt(jsonResponse.optString("code", "500"));
            } catch (NumberFormatException e) {
                code = 500;
            }

            String message = jsonResponse.optString("message", "删除失败");
            boolean success = code == 200 && jsonResponse.optBoolean("data", false);

            return new ApiResponse<>(code, message, success);
        } catch (JSONException e) {
            e.printStackTrace();
            return new ApiResponse<>(500, "解析删除响应失败：" + e.getMessage(), false);
        }
    }

}